<?php
/**
 * Created by Shy
 * Date 2020/12/1
 * Time 14:57
 */


namespace app\admin\model;


use think\facade\Cache;
use think\facade\Db;

class SysUser extends BasicModel
{
    protected $pk = 'id';
    protected $createTime = 'sign_up_at';

    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }

    /**
     * 子账户重置密码
     * User: 万奇
     * Date: 2021/2/6 0006
     * @param $param
     */
    public function user_reset_pwd($param){
        if ($param['pwd'] != $param['verify_pwd']){
            response(500, '两次密码不一致');
        }

        $this->where(['id' => $param['id']])->update(['password' => sha1($param['pwd'])]);
    }

    /**
     * 批量修改子账户 状态
     * User: 万奇
     * Date: 2021/2/6 0006
     * @param $param
     * @return SysUser
     */
    public function user_edit_disable($param){
        return $this->where([['id', 'in', implode(',', $param['id'])]])->update(['disable' => $param['disable']]);
    }

    /**
     * 获取子账户 信息
     * User: 万奇
     * Date: 2021/2/5 0005
     * @param $param
     * @return array|\think\Model|null
     * @throws \think\db\exception\DbException
     */
    public function get_user_info($param){
        $info       = $this->withoutField('password,token')->where(['id' => $param['id']])->find();
        $info['role_name']      = Db::name('sys_role')->where(['id' => $info['role_id']])->value('name');

        return $info;
    }

    /**
     * 新增 编辑 子账户
     * User: 万奇
     * Date: 2021/2/5 0005
     * @param $param
     * @param array $user_info
     */
    public function user_add($param, $user_info = []){
        if (is_exists($param['id'])){
            unset($param['phone'], $param['password']);
            $this->where(['id' => $param['id']])->strict(false)->update($param);
        } else{
            $param['id']                = uuid();
            $param['password']          = sha1($param['password']);
            $this->save($param);
        }
    }

    /**
     * 子账户列表
     * User: 万奇
     * Date: 2021/2/5 0005
     * @param $param
     * @return mixed
     */
    public function get_user_list($param){
        $where              = [];

        if (is_exists($param['role_id'])){
            $where[]        = ['a.role_id', '=', $param['role_id']];
        }

        if (is_exists($param['disable'], false, true)){
            $where[]        = ['a.disable', '=', $param['disable']];
        }

        if (is_exists($param['keyword'])){
            $where[]        = ['a.username|a.phone', 'like', "%{$param['keyword']}%"];
        }

        return $this->alias('a')
            ->field('a.id,a.username,a.phone,a.gender,a.department,a.is_main,a.disable,a.role_id,b.name role_name,a.create_at')
            ->join('sys_role b', 'a.role_id=b.id', 'left')
            ->where($where)
            ->order(['a.create_at' => 'desc'])
            ->group('a.id')
            ->paginate($param['limit'])
            ->toArray();
    }

    /**
     * 获取首页用户信息
     * User: 万奇
     * Date: 2020/12/30 0030
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function index_user_info($user_id){
        $data                   = [ 'host' => $_SERVER['SERVER_NAME'], 'ip' => get_ip(), 'product' => 'open'];
        $license                = json_decode(curl_request(\StaticData::RESOURCE_NAME['license_url'], $data), true);

        if ($license['status'] != 'success'){
            $license                = ['license' => '开源版', 'authorization' => '永久'];
        }

        $staff_model                =  new WxkStaff();
        $phone                      = $this->where(['id' => $user_id])->value('phone');
        $staff_info                 = $staff_model->get_staff_info(['phone' => $phone]);

        $result['phone']            = substr_replace($phone, '****', 3, 4);
        $result['license']          = $license['license'];
        $result['authorization']    = $license['authorization'];
        $result['company_name']     = isset($staff_info['company_name']) ? $staff_info['company_name'] : '';
        $result['section_name']     = isset($staff_info['section_name']) ? $staff_info['section_name'] : '';
        $result['name']             = isset($staff_info['name']) ? $staff_info['name'] : '';
        $result['avatar']           = isset($staff_info['avatar']) ? $staff_info['avatar'] : '';

        return $result;
    }

    /**
     * 退出登录
     * User: 万奇
     * Date: 2021/2/7 0007
     * @param $user_info
     */
    public function logout($user_info){
        $this->where(['id' => $user_info['user_id']])->update(['token' => sha1(md5(uuid()))]);
        Cache::delete('user_info_' . $user_info['user_id']);
    }

    public function UserRole()
    {
        return $this->hasOne(SysUserRole::class,'user_id','id');
    }

    /**
     * User: Shy
     * @param $user_id
     * @param $password
     * @param $transport_pass
     * @return bool
     */
    static function encryption($user_id, $password, $transport_pass)
    {
        if ($password == sha1($transport_pass)) {
            $token =  self::token();
             $update =  self::update(['id' => $user_id,'token' =>$token, 'last_login_at' => date('Y-m-d H:i:s', time())]);
             if($update){
                 return $token;
             }
        }
        return false;
    }

    /**
     * User:shy
     * 密钥
     * @return string
     */
    static function token(){
        return $uuid = sha1(md5(uuid()));
    }

    /**
     * User: Shy
     * @param $phone
     * @return bool
     */
    static function validatePhone($phone)
    {
        if (!preg_match("/^1[34578]\d{9}$/", $phone)) {
            return false;
        }
        return true;
    }
}